package com.gary.springcloud.call.service;

import com.gary.springcloud.call.entity.ExecutorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

/**
 * @author peng_rui
 * @date 2023/1/9
 */
@Slf4j
@Service
public class CommonService {

    @Autowired
    private ThService thService;

    public List<ExecutorResult> startService(Class<? extends Callable> classCallable) {
        //从数据库获取一个或多个数据 infoList
        List<String> infoList = new ArrayList<>();
        infoList.add("gary");
        infoList.add("rmy");
        infoList.add("hui");
        //遍历info 每个info 执行指定任务
        List<ExecutorResult> resultList = new ArrayList<ExecutorResult>();
        infoList.forEach(info -> {
            Callable callable;
            ExecutorResult executorResult = null;
            try {
                //通过反射创建callable 构造器
                Constructor callableConstructor =classCallable.getConstructor(String.class);
                //通过构造方法船舰callable实例
                callable = (Callable) callableConstructor.newInstance(info);

                //创建futureTask
                FutureTask<ExecutorResult> futureTask = new FutureTask<ExecutorResult>(callable);
                //交给线程池执行
                executorResult = thService.getExecutorResult(futureTask);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("构造方法创建失败,或实例化callable失败");
            }
            if (executorResult != null) {
                resultList.add(executorResult);
            }
        });
        return Collections.emptyList();
    }
}
